package com.tiantian.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.StrUtil;
import com.tiantian.api.RemoteUserService;
import com.tiantian.api.domain.vo.RemoteUserVo;
import com.tiantian.common.core.domain.ResponseResult;
import com.tiantian.common.core.domain.dto.MailRequestDTO;
import com.tiantian.common.core.enums.EmailType;
import com.tiantian.common.log.annotation.Log;
import com.tiantian.common.log.enums.BusinessType;
import com.tiantian.mail.config.properties.MailProperties;
import com.tiantian.mail.utils.MailUtils;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 邮件发送
 *
 * @author TianTian
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/mail")
public class MailController {


    private final MailProperties mailProperties;
    @DubboReference
    private RemoteUserService remoteUserService;

    @Value("${mail.brand}")
    private String brand;

    /**
     * 发送简单文字邮件
     *
     * @param mailRequestDTO 参数
     */
    @PostMapping("/sendAll")
    @SaCheckPermission("mail")
    @Log(businessType = BusinessType.EMAIL, isSaveResponseData = false)
    public ResponseResult<Void> sendAll(@RequestBody @Valid MailRequestDTO mailRequestDTO) {
        String mailType = mailRequestDTO.getType();
        if (!StrUtil.equalsAny(mailType,"text","html")) {
            return ResponseResult.fail("邮件类型格式不正确");
        }
        if (!mailProperties.getEnabled()) {
            return ResponseResult.fail("当前系统没有开启邮箱功能!");
        }
        // 群发
        sendAllEmail(mailRequestDTO);
        return ResponseResult.ok();
    }


    // 获取系统内所有新人用户的邮件并附上姓名
    @GetMapping("/all")
    @SaCheckPermission("mail")
    public ResponseResult<List<Map<String, String>>> getSystemAllEmail(){
        List<Map<String, String>> ajax = new ArrayList<>();
        List<RemoteUserVo> remoteUserVoList = remoteUserService.getNewcomerList(null);
        for (RemoteUserVo user : remoteUserVoList) {
            Map<String, String> map = new HashMap<>();
            map.put("email",user.getEmail());
            map.put("nickName",user.getNickName());
            ajax.add(map);
        }
        return ResponseResult.ok(ajax);
    }

    @Async
    public void sendAllEmail(MailRequestDTO mailRequestDTO) {
        MailUtils.send(
                mailRequestDTO.getTos(),
                mailRequestDTO.getSubject(),
                brand + mailRequestDTO.getContent(),
                EmailType.HTML.getType().equals(mailRequestDTO.getType())
        );
    }


}
